package 练习;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ConditionTest {
    final Lock lock = new ReentrantLock();
    // condition 依赖于 lock 来产生
    final Condition notFull = lock.newCondition();
    final Condition notEmpty = lock.newCondition();

    final Object[] items = new Object[100];
    int putptr, takeptr, count;

    public static void main(String[] args) throws InterruptedException {

        ConditionTest test = new ConditionTest();

        for (int i = 0; i < 1; i++) {
            int finalI = i;
            new Thread(() -> {
                Thread.interrupted();
                try {
                    test.put(String.format("数据%s", finalI));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }, String.format("线程【%s】", i)).start();
        }

        System.out.println();
        for (int i = 3; i < 4; i++) {
            new Thread(() -> {
                try {
                    System.out.println(test.take());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }, String.format("线程【%s】", i)).start();
        }
        
        System.out.println();
    }

    // 生产
    public void put(Object x) throws InterruptedException {
        lock.lock();
        try {
            //while (count == 1)
                // 调用await会阻塞当前线程 需要停止生成 并释放锁
                notFull.await();  // 队列已满，等待，直到 not full 才能继续生产
            items[putptr] = x;
            if (++putptr == items.length) putptr = 0;
            ++count;
            notEmpty.signal(); // 生产成功，队列已经 not empty 了，发个通知出去
        } catch (Exception e){
            System.out.println(e);
        } finally {
            lock.unlock();
            System.out.println();
        }
    }

    // 消费
    public Object take() throws InterruptedException {
        lock.lock();
        try {
//            while (count == 0)
//                notEmpty.await(); // 队列为空，等待，直到队列 not empty，才能继续消费
            Object x = items[takeptr];
            if (++takeptr == items.length) takeptr = 0;
            --count;
            notFull.signal(); // 被我消费掉一个，队列 not full 了，发个通知出去
            return x;
        } finally {
            lock.unlock();
        }
    }
}